import React, { PureComponent, Fragment } from 'react';
import { Card, Form, Row, Button, Input, Table, Divider, Popconfirm, Popover, Spin, message, Modal } from 'antd';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import moment from 'moment';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Ellipsis from '../../components/Ellipsis';
// import BizIcon from '../../components/BizIcon';
import { JobStatusMapper } from '../../utils/enum';
// import classNames from 'classnames';
import styles from './Job.less'

@connect(({ JobModel, loading }) => ({
  JobModel,
  quetyLoading: loading.effects['JobModel/findAllJob'],
  validatorCronLoading: loading.effects['JobModel/validatorCron'],
  batchSetJobStatusLoading: loading.effects['JobModel/batchSetJobStatus'],
}))
@Form.create()
export default class Job extends PureComponent {

  state = {
    screenHeight: document.documentElement.clientHeight,
  };

  // 数据初始化
  componentDidMount() {
    window.addEventListener('resize', this.handleHeight);
    const { dispatch } = this.props;
    dispatch({ type: 'JobModel/findAllJob' });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleHeight);
  }

  // 动态设置高度
  @Bind()
  @Debounce(400)
  handleHeight = () => {
    const screenHeight = document.documentElement.clientHeight;
    this.setState({ screenHeight });
  };

  // 查询数据
  findByPage = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    dispatch({ type: 'JobModel/findAllJob', payload: { ...queryParam, pageNo: 0 } });
    dispatch({ type: 'JobModel/save', payload: { selectedRowKeys: [] } });
  }

  // 查询表单
  queryForm() {
    const { form: { getFieldDecorator }, JobModel: { queryParam }, quetyLoading } = this.props;
    return (
      <Form onSubmit={this.findByPage} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="任务名称">
            {getFieldDecorator('jobName', { initialValue: queryParam.jobName })(
              <Input placeholder="任务名称(模糊匹配)" />
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={quetyLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  // 功能按钮
  actionButton() {
    const { dispatch, JobModel: { selectedRowKeys }, quetyLoading, batchSetJobStatusLoading } = this.props;
    const disabled = quetyLoading || (selectedRowKeys && selectedRowKeys.length <= 0);
    return (
      <Fragment>
        <Button.Group style={{ marginBottom: 8 }}>
          <Button
            icon="plus-circle"
            onClick={() => {
              dispatch(routerRedux.push('/alarm/job/list/add'));
            }}
          >
            <span style={{ marginLeft: 8 }}>新增</span>
          </Button>
          <Button
            icon="check-circle"
            disabled={disabled}
            onClick={() => {
              const modal = Modal.confirm({
                title: `确定启用这${selectedRowKeys.length}个告警?`,
                okText: '启用',
                cancelText: '取消',
                maskClosable: true,
                // visible: true,
                confirmLoading: batchSetJobStatusLoading,
                onOk() {
                  dispatch({
                    type: 'JobModel/batchSetJobStatus',
                    payload: { names: selectedRowKeys, status: 'enable' },
                    successCallBack: result => {
                      message.success(`启用成功 -> ${result.length}个`);
                      modal.destroy();
                    },
                  });
                },
                onCancel: () => modal.destroy(),
              });
            }}
          >
            <span style={{ marginLeft: 8 }}>启用</span>
          </Button>
          <Button
            icon="stop"
            disabled={disabled}
            onClick={() => {
              const modal = Modal.confirm({
                title: `确定禁用这${selectedRowKeys.length}个告警?`,
                okText: '禁用',
                cancelText: '取消',
                maskClosable: true,
                // visible: true,
                confirmLoading: batchSetJobStatusLoading,
                onOk() {
                  dispatch({
                    type: 'JobModel/batchSetJobStatus',
                    payload: { names: selectedRowKeys, status: 'disable' },
                    successCallBack: result => {
                      message.success(`禁用成功 -> ${result.length}个`);
                      modal.destroy();
                    },
                  });
                },
                onCancel: () => modal.destroy(),
              });
            }}
          >
            <span style={{ marginLeft: 8 }}>禁用</span>
          </Button>
          <Button
            icon="close-circle"
            disabled={disabled}
            onClick={() => {
              const modal = Modal.confirm({
                title: `确定删除这${selectedRowKeys.length}个告警?`,
                okText: '删除',
                cancelText: '取消',
                maskClosable: true,
                // visible: true,
                // confirmLoading: batchSetJobStatusLoading,
                onOk() {
                  dispatch({
                    type: 'JobModel/batchDelJob',
                    payload: { names: selectedRowKeys },
                    successCallBack: result => {
                      message.success(`删除成功 -> ${result.length}个`);
                      modal.destroy();
                    },
                  });
                },
                onCancel: () => modal.destroy(),
              });
            }}
          >
            <span style={{ marginLeft: 8 }}>删除</span>
          </Button>
        </Button.Group>
      </Fragment>
    );
  }

  // 数据表格
  getTable() {
    const { dispatch, JobModel, quetyLoading, validatorCronLoading } = this.props;
    let { screenHeight } = this.state;
    screenHeight -= 380;
    if (screenHeight < 200) screenHeight = 350;
    const columns = [
      { title: '告警任务名称', dataIndex: 'jobName', width: 200, render: val => <Link to={`/alarm/job/detail/${val}`} title="查看详情">{val}</Link> },
      {
        title: 'Cron表达式', dataIndex: 'cron', width: 180,
        render: val => {
          const content = (
            <Spin delay={100} spinning={validatorCronLoading}>
              {JobModel.cronTimeData.map(time => <div key={time}>{moment(time).format('YYYY-MM-DD HH:mm:ss')}</div>)}
            </Spin>
          );
          return (
            <Popover placement="right" content={content} title="接下来5次触发时间" trigger="click">
              <a title="点击查看触发时间" onClick={() => dispatch({ type: 'JobModel/validatorCron', payload: { cron: val, num: 5 } })}>{val}</a>
            </Popover>
          )
        },
      },
      { title: '任务实例数量', dataIndex: 'instanceCount', width: 150 },
      { title: '任务分片总数', dataIndex: 'shardingTotalCount', width: 150 },
      {
        title: '当前状态', dataIndex: 'status', width: 130,
        render: val => {
          let status = JobStatusMapper[val];
          if (!status) status = JobStatusMapper.error;
          return <span style={{ color: status.color }}>{status.label}</span>;
        },
      },
      { title: '说明', dataIndex: 'description', width: 450, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis> },
      {
        title: '操作', align: 'center', key: 'action', width: 180,
        render: (_, record) => (
          <Fragment>
            <Popconfirm
              placement="left"
              title={`确定要${record.status === "DISABLED" ? "启用" : "禁用"}该告警任务(${record.jobName})?`}
              okText={record.status === "DISABLED" ? "启用" : "禁用"}
              cancelText="取消"
              onConfirm={() => dispatch({
                type: 'JobModel/setJobStatus',
                payload: { name: record.jobName, status: record.status === "DISABLED" ? "enable" : "disable" },
                successCallBack: result => message.success((
                  <Fragment>
                    告警任务
                    <span style={{ color: '#f5222d' }}>{result.status === "DISABLED" ? "禁用" : "启用"}</span>
                    {`成功 -> ${result.jobName}`}
                  </Fragment>
                )),
              })}
            >
              <a>{record.status === "DISABLED" ? "启用" : "禁用"}</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => dispatch(routerRedux.push(`/alarm/job/edit/${record.jobName}`))}>
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="left"
              title={`确定删除该告警任务(${record.jobName})?`}
              okText="删除"
              cancelText="取消"
              onConfirm={() => dispatch({
                type: 'JobModel/delJob',
                payload: { name: record.jobName },
                successCallBack: result => message.success((
                  <Fragment>
                    告警任务
                    <span style={{ color: '#f5222d' }}>删除</span>
                    {`成功 -> ${result.jobBriefInfo.jobName}`}
                  </Fragment>
                )),
              })}
            >
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];
    return (
      <Table
        size="middle"
        bordered={true}
        rowKey={record => record.jobName}
        rowSelection={{
          fixed: false,
          selectedRowKeys: JobModel.selectedRowKeys,
          onChange: (_, selectedRows) => {
            const max = 50;
            if (selectedRows.length > max) {
              message.warning(`最多只能选择${max}个，当前选择${selectedRows.length}个`);
              return;
            }
            const selectedRowKeys = selectedRows.map(item => item.jobName);
            dispatch({ type: 'JobModel/save', payload: { selectedRowKeys } });
          },
        }}
        columns={columns}
        loading={quetyLoading}
        dataSource={JobModel.data}
        scroll={{ x: true, y: screenHeight }}
        pagination={{
          pageSize: 50,
          hideOnSinglePage: false,
          pageSizeOptions: ['30', '50', '100'],
          showSizeChanger: true, showQuickJumper: true,
          showTotal: totalTmp => `总记录数${totalTmp}条`,
        }}
      />
    );
  }

  render() {
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {this.actionButton()}
          {this.getTable()}
        </Card>
      </PageHeaderLayout>
    );
  }
}


